package com.mdd.front.service.course.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.config.GlobalConfig;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.course.*;
import com.mdd.common.entity.order.Order;
import com.mdd.common.entity.order.OrderCourse;
import com.mdd.common.enums.OrderEnum;
import com.mdd.common.mapper.course.CourseCommentImageMapper;
import com.mdd.common.mapper.course.CourseCommentMapper;
import com.mdd.common.mapper.course.CourseMapper;
import com.mdd.common.mapper.order.OrderCourseMapper;
import com.mdd.common.mapper.order.OrderMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.front.service.course.ICourseCommentService;
import com.mdd.front.validate.CourseCommentParam;
import com.mdd.front.validate.PageParam;
import com.mdd.front.vo.course.CourseCommentListVo;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 评论实现类
 * @author panweiliang
 */
@Service
public class CourseCommentServiceImpl implements ICourseCommentService {
        
    @Resource
    CourseCommentMapper courseCommentMapper;

    @Resource
    CourseCommentImageMapper courseCommentImageMapper;

    @Resource
    CourseMapper courseMapper;

    @Resource
    OrderMapper orderMapper;

    @Resource
    OrderCourseMapper orderCourseMapper;

    /**
     * 评论列表
     *
     * @author panweiliang
     * @param pageParam 分页参数
     * @param courseId 课程id
     * @return PageResult<CourseCommentListVo>
     */
    @Override
    public PageResult<CourseCommentListVo> list(PageParam pageParam, Integer courseId) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        MPJQueryWrapper<CourseComment> mpjQueryWrapper = new MPJQueryWrapper<CourseComment>()
                .selectAll(CourseComment.class)
                .select("user.avatar as userAvatar, user.nickname as userNickname, user.real_name as userRealName, course.name as courseName, course.cover as courseCoverPath")
                .innerJoin("?_user user ON user.id=t.user_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .innerJoin("?_course course ON course.id=t.course_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .eq("t.course_id", courseId)
                .orderByDesc(Arrays.asList("t.id"));

        IPage<CourseCommentListVo> iPage = courseCommentMapper.selectJoinPage(new Page<>(page, limit), CourseCommentListVo.class, mpjQueryWrapper);

        for(CourseCommentListVo item : iPage.getRecords()) {

            QueryWrapper<CourseCommentImage> commentImgQueryWrapper = new QueryWrapper<>();
            commentImgQueryWrapper.eq("comment_id", item.getId());

            List<CourseCommentImage> commentImageList = courseCommentImageMapper.selectList(commentImgQueryWrapper);

            List<String> commentImages = new LinkedList<>();

            commentImageList.forEach(imageItem -> {
                commentImages.add(UrlUtil.toAbsoluteUrl(imageItem.getUri()));
            });

            item.setCommentImgs(commentImages);
            item.setUserAvatar(UrlUtil.toAbsoluteUrl(item.getUserAvatar()));
            item.setCourseCoverPath(UrlUtil.toAbsoluteUrl(item.getCourseCoverPath()));
            item.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            item.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }


    /**
     * 评论新增
     *
     * @author panweiliang
     * @param courseCommentParam 参数
     */
    @Override
    public void add(CourseCommentParam courseCommentParam) {
        Course course = courseMapper.selectOne(
                new QueryWrapper<Course>()
                        .eq("id", courseCommentParam.getCourseId()));
        Assert.notNull(course, "课程不存在");
        Order order = orderMapper.selectOne(
                new QueryWrapper<Order>()
                        .eq("id", courseCommentParam.getOrderId()));

        Assert.notNull(order, "订单不存在");
        Assert.isTrue(order.getOrderStatus() == OrderEnum.ORDER_STATUS_COMPLETED.getCode(), "订单未完成支付，无法评价");
        OrderCourse orderCourse = orderCourseMapper.selectOne(
                new QueryWrapper<OrderCourse>()
                        .eq("course_id", courseCommentParam.getCourseId())
                        .eq("order_id", courseCommentParam.getOrderId())
        );
        Assert.notNull(orderCourse, "当前课程不属于当前订单");
        CourseComment courseComment = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                        .eq("user_id", courseCommentParam.getUserId())
                        .eq("course_id", courseCommentParam.getCourseId())
                        .eq("order_id", courseCommentParam.getOrderId())
        );
        Assert.isNull(courseComment, "已评价此订单，不能重复评价");
        CourseComment model = new CourseComment();
        model.setOrderId(courseCommentParam.getOrderId());
        model.setCourseId(courseCommentParam.getCourseId());
        model.setUserId(courseCommentParam.getUserId());
        model.setCourseScore(courseCommentParam.getCourseScore());
        model.setComment(courseCommentParam.getComment());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        int result = courseCommentMapper.insert(model);
        if (result > 0) {
            List<String> images = courseCommentParam.getImages();
            if(images != null) {
                images.forEach(item -> {
                    CourseCommentImage courseCommentImage = new CourseCommentImage();
                    courseCommentImage.setCommentId(model.getId());
                    courseCommentImage.setUri(UrlUtil.toRelativeUrl(item));
                    courseCommentImageMapper.insert(courseCommentImage);
                });
            }

        }
        orderCourse.setIsComment(1);
        this.orderCourseMapper.updateById(orderCourse);

    }


    /**
     * 评论删除
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        CourseComment model = courseCommentMapper.selectOne(
                new QueryWrapper<CourseComment>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        courseCommentMapper.delete(new QueryWrapper<CourseComment>().eq("id", id));

        courseCommentImageMapper.delete(new QueryWrapper<CourseCommentImage>().eq("comment_id", id));
    }

}
